<template>
  <div class="template-page">
    <div class="page-header">
      <button class="back-button" @click="goToHome">
        <span class="icon-arrow-left"></span>
        返回首页
      </button>
      <h1>消息模板</h1>
    </div>
    
    <div class="page-content">
      <div class="config-header">
        <p>管理系统中使用的各种消息模板，支持邮件、短信等多种类型</p>
        <button class="primary-btn" @click="showAddTemplateModal = true">
          <i class="icon-plus"></i> 新增模板
        </button>
      </div>
      
      <div class="card">
        <div class="filter-bar">
          <select v-model="selectedType" class="filter-select" @change="filterTemplates">
            <option value="">全部类型</option>
            <option value="email">邮件</option>
            <option value="sms">短信</option>
            <option value="system">系统消息</option>
          </select>
          
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索模板名称..."
            class="search-input"
            @keyup.enter="filterTemplates"
          >
          <button class="search-btn" @click="filterTemplates">搜索</button>
        </div>
        
        <div class="templates-grid">
          <div class="template-card" v-for="template in filteredTemplates" :key="template.id">
            <div class="template-header">
              <div class="template-type">
                <span :class="'type-tag type-' + template.type">
                  {{ template.type === 'email' ? '邮件' : template.type === 'sms' ? '短信' : '系统消息' }}
                </span>
              </div>
              <div class="template-status">
                <span :class="template.active ? 'status-active' : 'status-inactive'">
                  {{ template.active ? '启用' : '禁用' }}
                </span>
              </div>
            </div>
            
            <div class="template-body">
              <h3 class="template-title">{{ template.name }}</h3>
              <p class="template-desc">{{ template.description }}</p>
              
              <div class="template-preview">
                <p class="preview-label">预览：</p>
                <div class="preview-content">
                  {{ template.content.length > 100 ? template.content.substring(0, 100) + '...' : template.content }}
                </div>
              </div>
              
              <div class="template-variables" v-if="template.variables.length > 0">
                <p class="variables-label">可用变量：</p>
                <div class="variables-list">
                  <span class="variable-tag" v-for="varItem in template.variables" :key="varItem.key">
                    {{ varItem.key }}
                  </span>
                </div>
              </div>
            </div>
            
            <div class="template-footer">
              <button class="edit-btn" @click="editTemplate(template)">编辑</button>
              <button class="delete-btn" @click="deleteTemplate(template.id)">删除</button>
              <button 
                class="status-btn" 
                @click="toggleTemplateStatus(template.id)"
              >
                {{ template.active ? '禁用' : '启用' }}
              </button>
            </div>
          </div>
          
          <div class="empty-state" v-if="filteredTemplates.length === 0">
            <i class="icon-empty"></i>
            <p>暂无消息模板，请点击新增按钮创建</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑模板模态框 -->
    <div class="modal-overlay" v-if="showAddTemplateModal || showEditTemplateModal">
      <div class="modal">
        <div class="modal-header">
          <h3>{{ showEditTemplateModal ? '编辑消息模板' : '新增消息模板' }}</h3>
          <button class="close-btn" @click="closeTemplateModal">&times;</button>
        </div>
        <div class="modal-body">
          <form class="template-form">
            <div class="form-group">
              <label>模板名称 *</label>
              <input 
                type="text" 
                v-model="currentTemplate.name" 
                class="form-control"
                required
              >
            </div>
            
            <div class="form-group">
              <label>模板类型 *</label>
              <select v-model="currentTemplate.type" class="form-control" required>
                <option value="email">邮件</option>
                <option value="sms">短信</option>
                <option value="system">系统消息</option>
              </select>
            </div>
            
            <div class="form-group">
              <label>描述</label>
              <textarea 
                v-model="currentTemplate.description" 
                class="form-control"
                rows="2"
              ></textarea>
            </div>
            
            <div class="form-group" v-if="currentTemplate.type === 'email'">
              <label>邮件主题</label>
              <input 
                type="text" 
                v-model="currentTemplate.subject" 
                class="form-control"
              >
            </div>
            
            <div class="form-group">
              <label>模板内容 *</label>
              <textarea 
                v-model="currentTemplate.content" 
                class="form-control template-content"
                rows="6"
                required
              ></textarea>
            </div>
            
            <div class="variables-help">
              <p class="variables-title">可用变量：</p>
              <div class="variables-help-list">
                <span class="variable-help-tag" v-for="varItem in availableVariables" :key="varItem.key">
                  {{ varItem.key }}
                  <span class="variable-desc">{{ varItem.description }}</span>
                </span>
              </div>
              <p class="variables-note">使用方法：在模板中直接插入变量，如 &#123;&#123;ticketNumber&#125;&#125;</p>
            </div>
            
            <div class="form-group">
              <label class="checkbox-label">
                <input 
                  type="checkbox" 
                  v-model="currentTemplate.active"
                >
                启用该模板
              </label>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeTemplateModal">取消</button>
          <button class="primary-btn" @click="saveTemplate">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'MessageTemplate',
  data() {
    return {
      showAddTemplateModal: false,
      showEditTemplateModal: false,
      searchKeyword: '',
      selectedType: '',
      currentTemplate: {
        id: null,
        name: '',
        type: 'email',
        description: '',
        subject: '',
        content: '',
        active: true,
        variables: [
          { key: '{{ticketNumber}}', description: '工单编号' },
          { key: '{{title}}', description: '工单标题' },
          { key: '{{creator}}', description: '创建人' },
          { key: '{{createTime}}', description: '创建时间' }
        ]
      },
      availableVariables: [
        { key: '{{ticketNumber}}', description: '工单编号' },
        { key: '{{title}}', description: '工单标题' },
        { key: '{{creator}}', description: '创建人' },
        { key: '{{createTime}}', description: '创建时间' },
        { key: '{{handler}}', description: '处理人' },
        { key: '{{status}}', description: '工单状态' },
        { key: '{{priority}}', description: '优先级' }
      ],
      templates: [
        {
          id: 1,
          name: '新工单通知',
          type: 'email',
          description: '当有新工单创建时通知处理人',
          subject: '您有一个新的工单需要处理 (#{{ticketNumber}})',
          content: '您好，\n\n有一个新的工单需要您处理：\n工单编号：{{ticketNumber}}\n标题：{{title}}\n创建人：{{creator}}\n创建时间：{{createTime}}\n\n请及时处理。',
          active: true,
          variables: [
            { key: '{{ticketNumber}}', description: '工单编号' },
            { key: '{{title}}', description: '工单标题' },
            { key: '{{creator}}', description: '创建人' },
            { key: '{{createTime}}', description: '创建时间' }
          ]
        },
        {
          id: 2,
          name: '工单状态变更提醒',
          type: 'sms',
          description: '工单状态变更时通知工单创建人',
          subject: '',
          content: '您的工单{{ticketNumber}}状态已变更为{{status}}，处理人：{{handler}}。详情请登录系统查看。',
          active: true,
          variables: [
            { key: '{{ticketNumber}}', description: '工单编号' },
            { key: '{{status}}', description: '工单状态' },
            { key: '{{handler}}', description: '处理人' }
          ]
        },
        {
          id: 3,
          name: '工单超时提醒',
          type: 'system',
          description: '当工单即将超时或已超时时提醒处理人',
          subject: '',
          content: '警告：您处理的工单{{ticketNumber}}（{{title}}）即将在30分钟后超时，请尽快处理！',
          active: true,
          variables: [
            { key: '{{ticketNumber}}', description: '工单编号' },
            { key: '{{title}}', description: '工单标题' }
          ]
        }
      ]
    };
  },
  computed: {
    filteredTemplates() {
      return this.templates.filter(template => {
        const matchesType = !this.selectedType || template.type === this.selectedType;
        const matchesSearch = !this.searchKeyword || 
          template.name.toLowerCase().includes(this.searchKeyword.toLowerCase()) ||
          template.description.toLowerCase().includes(this.searchKeyword.toLowerCase());
        return matchesType && matchesSearch;
      });
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    filterTemplates() {
      // 过滤逻辑在计算属性中实现
    },
    editTemplate(template) {
      this.currentTemplate = JSON.parse(JSON.stringify(template));
      this.showEditTemplateModal = true;
    },
    deleteTemplate(id) {
      if (confirm('确定要删除这个消息模板吗？')) {
        this.templates = this.templates.filter(tpl => tpl.id !== id);
      }
    },
    toggleTemplateStatus(id) {
      const template = this.templates.find(tpl => tpl.id === id);
      if (template) {
        template.active = !template.active;
      }
    },
    closeTemplateModal() {
      this.showAddTemplateModal = false;
      this.showEditTemplateModal = false;
      this.resetCurrentTemplate();
    },
    resetCurrentTemplate() {
      this.currentTemplate = {
        id: null,
        name: '',
        type: 'email',
        description: '',
        subject: '',
        content: '',
        active: true,
        variables: [
          { key: '{{ticketNumber}}', description: '工单编号' },
          { key: '{{title}}', description: '工单标题' },
          { key: '{{creator}}', description: '创建人' },
          { key: '{{createTime}}', description: '创建时间' }
        ]
      };
    },
    saveTemplate() {
      // 简单验证
      if (!this.currentTemplate.name.trim()) {
        alert('请输入模板名称');
        return;
      }
      
      if (!this.currentTemplate.content.trim()) {
        alert('请输入模板内容');
        return;
      }
      
      // 复制可用变量
      this.currentTemplate.variables = [...this.availableVariables];
      
      if (this.showEditTemplateModal) {
        // 更新现有模板
        const index = this.templates.findIndex(tpl => tpl.id === this.currentTemplate.id);
        if (index !== -1) {
          this.templates.splice(index, 1, JSON.parse(JSON.stringify(this.currentTemplate)));
        }
      } else {
        // 添加新模板
        this.currentTemplate.id = Date.now();
        this.templates.push(JSON.parse(JSON.stringify(this.currentTemplate)));
      }
      
      this.closeTemplateModal();
    }
  }
}
</script>

<style scoped>
.template-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1e5e8;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.page-content {
  margin-top: 20px;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.config-header p {
  color: #666;
  font-size: 14px;
}

.card {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.filter-select {
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
  background-color: white;
}

.search-input {
  flex: 1;
  min-width: 200px;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.search-btn {
  padding: 10px 20px;
  background: #f5f7fa;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background: #e9ecef;
}

.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.template-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
}

.template-card:hover {
  box-shadow: 0 3px 15px rgba(0, 0, 0, 0.07);
  transform: translateY(-3px);
}

.template-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #f9fafb;
  border-bottom: 1px solid #f0f0f0;
}

.type-tag {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.type-email {
  background-color: #e3f2fd;
  color: #1976d2;
}

.type-sms {
  background-color: #e8f5e9;
  color: #388e3c;
}

.type-system {
  background-color: #fff8e1;
  color: #f57c00;
}

.status-active, .status-inactive {
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #e8f5e9;
  color: #388e3c;
}

.status-inactive {
  background-color: #f5f5f5;
  color: #757575;
}

.template-body {
  padding: 15px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.template-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #333;
}

.template-desc {
  margin: 0 0 15px 0;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

.template-preview {
  margin-bottom: 15px;
}

.preview-label {
  margin: 0 0 5px 0;
  font-size: 13px;
  font-weight: 500;
  color: #555;
}

.preview-content {
  margin: 0;
  font-size: 13px;
  color: #444;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
  border: 1px solid #f0f0f0;
  white-space: pre-line;
  line-height: 1.4;
  max-height: 80px;
  overflow-y: auto;
}

.template-variables {
  margin-top: auto;
}

.variables-label {
  margin: 0 0 5px 0;
  font-size: 13px;
  font-weight: 500;
  color: #555;
}

.variables-list {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.variable-tag {
  font-size: 11px;
  padding: 2px 6px;
  background-color: #f0f5ff;
  color: #1976d2;
  border-radius: 3px;
}

.template-footer {
  display: flex;
  justify-content: space-between;
  padding: 10px 15px;
  background-color: #f9fafb;
  border-top: 1px solid #f0f0f0;
  gap: 5px;
}

.edit-btn, .delete-btn, .status-btn {
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
  border: none;
  flex: 1;
  max-width: 33%;
  white-space: nowrap;
}

.edit-btn {
  background-color: #e3f2fd;
  color: #1976d2;
}

.edit-btn:hover {
  background-color: #bbdefb;
}

.delete-btn {
  background-color: #ffebee;
  color: #d32f2f;
}

.delete-btn:hover {
  background-color: #ffcdd2;
}

.status-btn {
  background-color: #f5f5f5;
  color: #555;
}

.status-btn:hover {
  background-color: #e9e9e9;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 0;
  color: #999;
}

.icon-empty::before {
  content: "✉️";
  font-size: 48px;
  display: block;
  margin-bottom: 15px;
}

.primary-btn {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.primary-btn:hover {
  background: #2980b9;
}

.icon-plus::before {
  content: "+";
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 10px;
  width: 700px;
  max-width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
}

.modal-header {
  padding: 15px 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 20px;
}

.template-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-group label {
  font-weight: 500;
  font-size: 14px;
}

.form-control {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.template-content {
  font-family: monospace;
  resize: vertical;
}

.variables-help {
  background-color: #f9fafb;
  border-radius: 5px;
  padding: 15px;
  margin-top: 10px;
}

.variables-title {
  margin: 0 0 10px 0;
  font-size: 14px;
  font-weight: 600;
  color: #555;
}

.variables-help-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.variable-help-tag {
  display: inline-flex;
  flex-direction: column;
  font-size: 12px;
  min-width: 120px;
}

.variable-desc {
  font-size: 11px;
  color: #666;
}

.variables-note {
  margin: 0;
  font-size: 12px;
  color: #777;
  font-style: italic;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.modal-footer {
  padding: 15px 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  padding: 8px 15px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn:hover {
  background: #e9e9e9;
}

.icon-arrow-left::before {
  content: "←";
}
</style>